<script setup>
import { ref, onMounted } from 'vue'
import request, { SERVER_BASE_URL } from "@/utils/request.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Hide, View, Plus } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const currentUser = ref(userStore.getUserInfo || JSON.parse(localStorage.getItem('user') || '{}'));
const articles = ref([]);
const loading = ref(false);
const loadingStatus = ref(false);

// 编辑文章相关变量
const showEditDialog = ref(false);
const editForm = ref({
  id: null,
  content: '',
  status: ''
});
const currentEditMedia = ref([]);  // 当前编辑文章的媒体列表
const uploadFiles = ref([]);       // 新上传的文件
const mediaTypes = ref([]);        // 新上传文件的类型
const toDeleteMediaIds = ref([]);  // 要删除的媒体ID

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  } else if(url.startsWith('uploads/')){
    fullUrl = serverBaseUrl + '/' + url;
  }

  return fullUrl;
};

// 获取用户文章列表
const fetchUserArticles = async () => {
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.warning('请先登录');
    return;
  }

  loading.value = true;
  try {
    const { code, data } = await request.get(`/article/user/${currentUser.value.id}`);
    if (code === 200) {
      articles.value = data;
    }
  } catch (error) {
    console.error('获取文章失败:', error);
    ElMessage.error('获取文章失败');
  } finally {
    loading.value = false;
  }
};

// 删除文章
const deleteArticle = (id) => {
  ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const { code, msg } = await request.delete(`/article/delete/${id}`);
      if (code === 200) {
        ElMessage.success('删除成功');
        fetchUserArticles(); // 刷新列表
      } else {
        ElMessage.error(msg || '删除失败');
      }
    } catch (error) {
      console.error('删除文章失败:', error);
      ElMessage.error('删除文章失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 更改文章状态 - 简化为直接切换发布或隐藏
const toggleArticleVisibility = async (article) => {
  if (loadingStatus.value) return;
  
  // 确定要切换到的状态
  const newStatus = article.status === 'PUBLISHED' ? 'HIDDEN' : 'PUBLISHED';
  
  loadingStatus.value = true;
  try {
    const { code, msg } = await request.put('/article/update', {
      id: article.id,
      status: newStatus
    });
    
    if (code === 200) {
      ElMessage.success(newStatus === 'PUBLISHED' ? '文章已发布' : '文章已隐藏');
      article.status = newStatus; // 更新本地状态
    } else {
      ElMessage.error(msg || '状态修改失败');
    }
  } catch (error) {
    console.error('修改状态失败:', error);
    ElMessage.error('修改状态失败');
  } finally {
    loadingStatus.value = false;
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'PUBLISHED': return 'success';
    case 'DRAFT': return 'info';
    case 'HIDDEN': return 'warning';
    default: return '';
  }
};

// 跳转到文章详情
const viewArticleDetail = (id) => {
  window.open(`/article/${id}`, '_blank');
};

// 获取文章第一张预览图
const getFirstImage = (mediaList) => {
  if (!mediaList || !mediaList.length) return null;
  
  const images = mediaList.filter(media => media.mediaType === 'IMAGE');
  return images.length > 0 ? images[0].mediaUrl : null;
};

// 打开编辑对话框
const openEditDialog = (article) => {
  editForm.value = {
    id: article.id,
    content: article.content,
    status: article.status
  };
  
  // 复制文章媒体列表
  currentEditMedia.value = article.mediaList ? [...article.mediaList] : [];
  uploadFiles.value = [];
  mediaTypes.value = [];
  toDeleteMediaIds.value = [];
  
  showEditDialog.value = true;
};

// 处理文件上传前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isVideo = file.type.startsWith('video/');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage && !isVideo) {
    ElMessage.error('只能上传图片或视频文件!');
    return false;
  }
  
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }
  
  // 检查媒体文件总数量限制
  if (currentEditMedia.value.length + uploadFiles.value.length >= 9) {
    ElMessage.warning('最多只能上传9个媒体文件!');
    return false;
  }
  
  // 记录媒体类型
  const mediaType = isImage ? 'IMAGE' : 'VIDEO';
  mediaTypes.value.push(mediaType);
  
  return true;
};

// 处理文件变化
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList;
  // 确保mediaTypes数组长度与fileList一致
  while (mediaTypes.value.length < fileList.length) {
    const file = fileList[mediaTypes.value.length];
    const isImage = file.raw.type.startsWith('image/');
    mediaTypes.value.push(isImage ? 'IMAGE' : 'VIDEO');
  }
};

// 移除上传文件
const removeUpload = (file, fileList) => {
  const index = uploadFiles.value.findIndex(item => item.uid === file.uid);
  if (index !== -1) {
    uploadFiles.value.splice(index, 1);
    mediaTypes.value.splice(index, 1);
  }
};

// 从现有媒体中移除
const removeCurrentMedia = (media) => {
  const index = currentEditMedia.value.findIndex(m => m.id === media.id);
  if (index !== -1) {
    currentEditMedia.value.splice(index, 1);
    toDeleteMediaIds.value.push(media.id); // 添加到待删除列表
  }
};

// 提交文章编辑
const submitEdit = async () => {
  if (!editForm.value.content.trim()) {
    ElMessage.warning('文章内容不能为空');
    return;
  }
  
  try {
    const formData = new FormData();
    formData.append('article', new Blob([JSON.stringify(editForm.value)], {
      type: 'application/json'
    }));
    
    // 添加要删除的媒体ID
    if (toDeleteMediaIds.value.length > 0) {
      formData.append('deleteMediaIds', new Blob([JSON.stringify(toDeleteMediaIds.value)], {
        type: 'application/json'
      }));
    }
    
    // 添加新媒体文件
    uploadFiles.value.forEach((file, index) => {
      const rawFile = file.raw;
      if (rawFile) {
        formData.append('mediaFiles', rawFile);
        formData.append('mediaTypes', mediaTypes.value[index]);
      }
    });

    const response = await request.post('/article/update-with-media', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response.code === 200) {
      ElMessage.success('文章更新成功');
      showEditDialog.value = false;
      fetchUserArticles(); // 刷新文章列表
    } else {
      ElMessage.error(response.msg || '更新失败');
    }
  } catch (error) {
    console.error('更新文章失败:', error);
    ElMessage.error('更新文章失败');
  }
};

onMounted(() => {
  fetchUserArticles();
});
</script>

<template>
  <div class="my-article-container">
    <el-card class="my-article-card">
    <h2 class="page-title">我的文章</h2>

    <!-- 加载中状态 -->
    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="articles.length === 0" description="暂无文章" />

    <!-- 文章列表 -->
    <div v-else class="article-list">
      <el-card v-for="article in articles" :key="article.id" class="article-card">
        <div class="article-card-content">
          <!-- 文章信息 -->
          <div class="article-info">
            <div class="article-header">
              <span class="article-time">发布于: {{ new Date(article.createTime).toLocaleDateString() }}</span>
              <el-tag :type="getStatusTagType(article.status)" size="small">
                {{ article.status === 'PUBLISHED' ? '已发布' : article.status === 'DRAFT' ? '草稿' : '已隐藏' }}
              </el-tag>
            </div>
            
            <div class="article-body" @click="viewArticleDetail(article.id)">
              <div class="content-text">{{ article.content }}</div>
              <div v-if="getFirstImage(article.mediaList)" class="content-image">
                <el-image 
                  :src="getImgUrl(getFirstImage(article.mediaList))" 
                  fit="cover" 
                  :preview-src-list="article.mediaList.filter(m => m.mediaType === 'IMAGE').map(m => getImgUrl(m.mediaUrl))"
                />
              </div>
            </div>
            
            <div class="article-footer">
              <div class="article-stats">
                <!-- <span>浏览: {{ article.views }}</span> -->
                <span>点赞: {{ article.likes }}</span>
                <span>评论: {{ article.commentCount }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="article-actions">
            <el-tooltip content="编辑" placement="top">
              <el-button type="primary" :icon="Edit" circle size="small" @click="openEditDialog(article)" style="margin: 0" />
            </el-tooltip>
            
            <el-tooltip :content="article.status === 'PUBLISHED' ? '隐藏文章' : '发布文章'" placement="top">
              <el-button 
                :type="article.status === 'PUBLISHED' ? 'info' : 'success'" 
                :icon="article.status === 'PUBLISHED' ? Hide : View"
                circle 
                size="small" 
                @click="toggleArticleVisibility(article)"
                style="margin: 0"
              />
            </el-tooltip>
            
            <el-tooltip content="删除" placement="top">
              <el-button style="margin: 0" type="danger" :icon="Delete" circle size="small" @click="deleteArticle(article.id)" />
            </el-tooltip>
          </div>
        </div>
      </el-card>
    </div>
    </el-card>

    <!-- 编辑文章对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑文章"
      width="500px"
      destroy-on-close
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="文章内容">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="4"
            placeholder="文章内容..."
          ></el-input>
        </el-form-item>
        
        <el-form-item label="当前媒体" v-if="currentEditMedia.length > 0">
          <div class="media-preview-list">
            <div v-for="media in currentEditMedia" :key="media.id" class="media-preview-item">
              <img v-if="media.mediaType === 'IMAGE'" :src="getImgUrl(media.mediaUrl)" alt="图片">
              <video v-else-if="media.mediaType === 'VIDEO'" controls>
                <source :src="getImgUrl(media.mediaUrl)" type="video/mp4">
              </video>
              <div class="media-preview-remove" @click="removeCurrentMedia(media)">
                <el-icon><Delete /></el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="上传媒体">
          <el-upload
            action=""
            :auto-upload="false"
            :file-list="uploadFiles"
            :on-remove="removeUpload"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            multiple
            list-type="picture-card"
            :limit="9 - currentEditMedia.length"
            :on-exceed="() => ElMessage.warning('最多只能上传9个媒体文件!')"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">最多上传9个媒体文件，支持图片和视频，单个文件不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="文章状态">
          <el-select v-model="editForm.status" placeholder="选择状态">
            <el-option label="已发布" value="PUBLISHED"></el-option>
            <el-option label="草稿" value="DRAFT"></el-option>
            <el-option label="隐藏" value="HIDDEN"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.my-article-container {
  min-width: 90%;
  margin: 0 auto;
  padding: 20px;
}

.my-article-card  {
  border-radius: 12px;
  min-height: 80vh;
}

.page-title {
  font-size: 20px;
  color: #333;
  padding: 0;
  margin-top: 0;
  margin-bottom: 20px;
}

.loading-state {
  padding: 20px;
}

.article-list {
  margin-right: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-card {

  transition: all 0.3s ease;
}

.article-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-card-content {
  display: flex;
  justify-content: space-between;
}

.article-info {
  flex: 1;
  overflow: hidden;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.article-time {
  color: #909399;
  font-size: 13px;
}

.article-body {
  display: flex;
  cursor: pointer;
}

.content-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  color: #333;
  margin-right: 12px;
}

.content-image {
  width: 100px;
  height: 100px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.content-image .el-image {
  width: 100%;
  height: 100%;
}

.article-footer {
  margin-top: 12px;
}

.article-stats {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 12px;
}

.article-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 12px;
}

.media-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.media-preview-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
}

.media-preview-item img,
.media-preview-item video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.media-preview-remove {
  position: absolute;
  right: 4px;
  top: 4px;
  width: 20px;
  height: 20px;
  background: rgba(0,0,0,0.5);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.media-preview-remove:hover {
  background: rgba(255,0,0,0.7);
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>

